package com.blackhorse.simple;

import com.blackhorse.utils.ConnectionUtils;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

//消息生成者
public class Consumer {

    public static void main(String[] args) {
        Connection connection = null;
        Channel channel = null;
        try {
            //获取连接
            connection = ConnectionUtils.getConnection();
            //创建频道
            channel = connection.createChannel();
            //创建消费者，并设计消息处理
            channel.queueDeclare(Producer.QUEUE_NAME,
                    true,
                    false,
                    false,
                    null);
            //创建消费者，指定监听策略
            DefaultConsumer consumer = new DefaultConsumer(channel) {
                //consumerTag：消息标签，在channel.basicConsume时候可以指定
                //envolope：消息包内容，可从中获取消息id，消息routingkey，交换机，消息和重传标记（收到消息失败后是否需要重新发送）
                //properties：消息属性
                //body：消息
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    System.out.println("路由key为：" + envelope.getRoutingKey());
                    System.out.println("交换机为：" + envelope.getExchange());
                    System.out.println("消息id：" + envelope.getDeliveryTag());
                    System.out.println("收到的消息：" + new String(body, "UTF-8"));
                    System.out.println("\n-----------------------------------------------------\n");
                }
            };
            //监听消息
            channel.basicConsume(Producer.QUEUE_NAME, //队列名称
                    true, //是否自动确认，自动确认时会向MQ回复收到了，MQ收到回复后会删出这个消息。设为false则需要手动确认
                    consumer);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } finally {
            //不关闭资源，应该一直监听消息
            //ConnectionUtils.close(channel, connection);
        }

    }
}
